<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">车位管理</h1>
    </div>

    <!-- 操作按钮栏和搜索栏 -->
    <div class="action-bar">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <IconifyIconOffline icon="ep:plus" />
          添加
        </el-button>
        <el-button type="success" @click="showImportDialog">
          <IconifyIconOffline icon="ep:upload" />
          导入
        </el-button>
        <el-button
          :disabled="selectedRows.length === 0"
          @click="handleBatchBindChargeStandard"
        >
          <IconifyIconOffline icon="ep:money" />
          添加收费标准
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedRows.length === 0"
          @click="handleBatchDelete"
        >
          <IconifyIconOffline icon="ep:delete" />
          删除
        </el-button>
      </div>
      
      <div class="search-filters">
        <el-input
          v-model="searchForm.spaceNo"
          placeholder="车位编号"
          style="width: 140px;"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-select
          v-model="searchForm.cellId"
          placeholder="小区"
          style="width: 140px;"
          clearable
        >
          <el-option
            v-for="cell in cellList"
            :key="cell.id"
            :label="cell.name"
            :value="cell.id"
          />
        </el-select>
        <el-select
          v-model="searchForm.type"
          placeholder="车位类型"
          style="width: 120px;"
          clearable
        >
          <el-option label="产权车位" :value="1" />
          <el-option label="公共车位" :value="2" />
          <el-option label="租赁车位" :value="3" />
          <el-option label="访客车位" :value="4" />
          <el-option label="其他" :value="5" />
        </el-select>
        <el-select
          v-model="searchForm.status"
          placeholder="车位状态"
          style="width: 120px;"
          clearable
        >
          <el-option label="空置" :value="1" />
          <el-option label="自用" :value="2" />
          <el-option label="出租" :value="3" />
          <el-option label="出售" :value="4" />
          <el-option label="占用" :value="5" />
          <el-option label="报废" :value="6" />
        </el-select>
        <el-button type="primary" @click="handleSearch">
          <IconifyIconOffline icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="handleReset">
          <IconifyIconOffline icon="ep:refresh" />
          重置
        </el-button>
      </div>
    </div>

    <!-- 车位列表表格 -->
    <div v-loading="loading" class="table-container">
      <el-table
        ref="tableRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="spaceNo" label="车位编号" width="120" />
        <el-table-column prop="cellName" label="所属小区" width="150" />
        <el-table-column prop="type" label="车位类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="车位状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="车位面积" width="120">
          <template #default="{ row }">
            {{ row.area ? `${row.area}m²` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="chargeStandardCount" label="收费标准个数" width="140" />
        <el-table-column prop="chargeStandards" label="收费金额" width="200">
          <template #default="{ row }">
            {{ row.chargeStandards || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button link type="primary" @click="handleBindResident(row)">
              绑定住户
            </el-button>
            <el-button link type="primary" @click="handleBindVehicle(row)">
              绑定车辆
            </el-button>
            <el-button link type="primary" @click="handleAddChargingStandard(row)">
              添加收费标准
            </el-button>
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 筛选对话框 -->
    <el-dialog
      v-model="showFilterDialog"
      title="筛选条件"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="小区">
          <el-select
            v-model="filterForm.cellId"
            placeholder="请选择小区"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="cell in cellList"
              :key="cell.id"
              :label="cell.name"
              :value="cell.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位类型">
          <el-select
            v-model="filterForm.type"
            placeholder="请选择车位类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in PARKING_SPACE_TYPE_LABELS"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择车位状态"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in PARKING_SPACE_STATUS_LABELS"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFilterDialog = false">取消</el-button>
        <el-button type="primary" @click="handleFilter">确定</el-button>
      </template>
    </el-dialog>

    <!-- 车位表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="车位编号" prop="spaceNo">
          <el-input v-model="formData.spaceNo" placeholder="请输入车位编号" />
        </el-form-item>
        <el-form-item label="所属小区" prop="cellId">
          <el-select
            v-model="formData.cellId"
            placeholder="请选择小区"
            style="width: 100%"
          >
            <el-option
              v-for="cell in cellList"
              :key="cell.id"
              :label="cell.name"
              :value="cell.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位类型" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择车位类型"
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in PARKING_SPACE_TYPE_LABELS"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择车位状态"
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in PARKING_SPACE_STATUS_LABELS"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位面积" prop="area">
          <el-input-number
            v-model="formData.area"
            :min="0"
            :precision="2"
            placeholder="请输入车位面积"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="具体位置" prop="location">
          <el-input
            v-model="formData.location"
            placeholder="请输入车位具体位置"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注信息"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 车位详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="车位详情"
      width="600px"
      :close-on-click-modal="true"
    >
      <div v-loading="detailLoading" class="detail-content">
        <div v-if="detailData" class="detail-info">
          <div class="detail-row">
            <span class="label">车位编号：</span>
            <span class="value">{{ detailData.spaceNo }}</span>
          </div>
          <div class="detail-row">
            <span class="label">所属小区：</span>
            <span class="value">{{ detailData.cellName }}</span>
          </div>
          <div class="detail-row">
            <span class="label">车位类型：</span>
            <span class="value">
              <el-tag :type="getTypeTagType(detailData.type)">
                {{ getTypeLabel(detailData.type) }}
              </el-tag>
            </span>
          </div>
          <div class="detail-row">
            <span class="label">车位状态：</span>
            <span class="value">
              <el-tag :type="getStatusTagType(detailData.status)">
                {{ getStatusLabel(detailData.status) }}
              </el-tag>
            </span>
          </div>
          <div class="detail-row">
            <span class="label">车位面积：</span>
            <span class="value">{{ detailData.area }}m²</span>
          </div>
          <div class="detail-row">
            <span class="label">收费标准：</span>
            <div class="value">
              <div v-if="detailChargeStandards.length > 0" class="charge-standards-list">
                <div 
                  v-for="standard in detailChargeStandards" 
                  :key="standard.id" 
                  class="charge-standard-item"
                >
                  <span class="standard-info">
                    {{ standard.name }}: {{ standard.pricestr }}
                  </span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="handleUnbindChargeStandard(standard.id)"
                    :loading="unbindLoading"
                  >
                    解除绑定
                  </el-button>
                </div>
              </div>
              <span v-else>暂无</span>
            </div>
          </div>
          <div class="detail-row">
            <span class="label">车位位置：</span>
            <span class="value">{{ detailData.location || '暂无' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">备注：</span>
            <span class="value">{{ detailData.remark || '暂无' }}</span>
          </div>
          <div class="detail-row" v-if="detailData.ownerName">
            <span class="label">所属业主：</span>
            <div class="value">
              <div class="bound-owner-item">
                <span class="owner-info">
                  {{ detailData.ownerName }}
                </span>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleUnbindOwner"
                  :loading="ownerUnbindLoading"
                >
                  解绑
                </el-button>
              </div>
            </div>
          </div>
          <div class="detail-row">
            <span class="label">绑定车辆：</span>
            <div class="value">
              <div v-if="detailBoundVehicles.length > 0" class="bound-vehicles-list">
                <div
                  v-for="vehicle in detailBoundVehicles"
                  :key="vehicle.vehicleId"
                  class="bound-vehicle-item"
                >
                  <span class="vehicle-info">
                    {{ vehicle.plateNo }}
                  </span>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleUnbindVehicle(vehicle.vehicleId)"
                    :loading="vehicleUnbindLoading"
                  >
                    解绑
                  </el-button>
                </div>
              </div>
              <span v-else>暂无</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 绑定车辆弹窗 -->
    <el-dialog v-model="bindVehicleDialogVisible" title="绑定车辆" width="600px" :close-on-click-modal="true">
      <el-form
        ref="bindVehicleFormRef"
        :model="bindVehicleForm"
        :rules="bindVehicleFormRules"
        label-width="120px"
      >
        <el-form-item label="车位ID" prop="parkingSpaceId">
          <el-input v-model="bindVehicleForm.parkingSpaceId" disabled />
        </el-form-item>
        <el-form-item label="选择车辆" prop="vehicleId">
          <el-select
            v-model="bindVehicleForm.vehicleId"
            placeholder="请输入车牌号搜索车辆"
            style="width: 100%"
            filterable
            remote
            :remote-method="searchVehicles"
            :loading="vehicleSearchLoading"
            clearable
          >
            <el-option
              v-for="vehicle in vehicleList"
              :key="vehicle.id"
              :label="`${vehicle.plateNo} - ${vehicle.ownerName}`"
              :value="vehicle.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定类型" prop="bindType">
          <el-select v-model="bindVehicleForm.bindType" placeholder="请选择绑定类型" style="width: 100%">
            <el-option label="长期绑定" :value="1" />
            <el-option label="临时绑定" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="授权开始时间" prop="authorizeStart">
          <el-date-picker
            v-model="bindVehicleForm.authorizeStart"
            type="datetime"
            placeholder="请选择授权开始时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledStartDate"
            :disabled-time="disabledStartTime"
          />
        </el-form-item>
        <el-form-item label="授权结束时间" prop="authorizeEnd">
          <el-date-picker
            v-model="bindVehicleForm.authorizeEnd"
            type="datetime"
            placeholder="请选择授权结束时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledEndDate"
            :disabled-time="disabledEndTime"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindVehicleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindVehicleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 绑定住户弹窗 -->
    <el-dialog v-model="bindOwnerDialogVisible" title="绑定住户" width="600px" :close-on-click-modal="true">
      <div class="bind-owner-content">
        <div class="search-section">
          <el-input
            v-model="ownerSearchKeyword"
            placeholder="请输入业主姓名进行搜索"
            clearable
            @input="searchOwners"
            @clear="ownerList = []"
          >
            <template #prefix>
              <IconifyIconOffline icon="ep:search" />
            </template>
          </el-input>
        </div>
        
        <div class="owner-list-section" v-if="ownerList.length > 0">
          <h4>搜索结果：</h4>
          <div class="owner-list">
            <div
              v-for="owner in ownerList"
              :key="owner.id"
              class="owner-item"
              :class="{ active: selectedOwnerId === owner.id }"
              @click="selectedOwnerId = owner.id"
            >
              <div class="owner-name">{{ owner.name }}</div>
            </div>
          </div>
        </div>
        
        <div class="no-results" v-else-if="ownerSearchKeyword && !ownerSearchLoading">
          <el-empty description="未找到相关业主" />
        </div>
        
        <div class="loading" v-if="ownerSearchLoading">
          <el-loading-directive />
          <span>搜索中...</span>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="bindOwnerDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          :disabled="!selectedOwnerId"
          :loading="bindOwnerLoading"
          @click="confirmBindOwner"
        >
          确定绑定
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加收费标准弹窗 -->
    <el-dialog v-model="addChargeStandardDialogVisible" title="添加收费标准" width="600px" :close-on-click-modal="true">
      <el-form
        ref="chargeStandardFormRef"
        :model="chargeStandardForm"
        :rules="chargeStandardFormRules"
        label-width="120px"
      >
        <el-form-item label="车位ID" prop="parkingSpaceId">
          <el-input v-model="chargeStandardForm.parkingSpaceId" disabled />
        </el-form-item>
        
        <el-form-item label="收费类型" prop="chargeTypeId">
          <el-select 
            v-model="selectedChargeType" 
            placeholder="请选择收费类型" 
            style="width: 100%"
            @change="handleChargeTypeChange"
          >
            <el-option
              v-for="type in chargeTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="收费项目" prop="chargeItemId">
          <el-select 
            v-model="selectedChargeItem" 
            placeholder="请选择收费项目" 
            style="width: 100%"
            :disabled="!selectedChargeType"
            @change="handleChargeItemChange"
          >
            <el-option
              v-for="item in chargeItems"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="收费标准" prop="chargeStandardId">
          <el-select 
            v-model="selectedChargeStandard" 
            placeholder="请选择收费标准" 
            style="width: 100%"
            :disabled="!selectedChargeItem"
            @change="handleChargeStandardChange"
          >
            <el-option
              v-for="standard in chargeStandards"
              :key="standard.id"
              :label="standard.name"
              :value="standard.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="金额" prop="amountOverride">
          <el-input-number
            v-model="chargeStandardForm.amountOverride"
            :min="0"
            :precision="2"
            placeholder="请输入金额"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="当前是否可用" prop="isCurrent">
          <el-radio-group v-model="chargeStandardForm.isCurrent">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addChargeStandardDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddChargeStandardSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加收费标准弹窗 -->
    <el-dialog v-model="batchBindChargeStandardDialogVisible" title="添加收费标准" width="600px" :close-on-click-modal="true">
      <el-form
        ref="batchBindChargeStandardFormRef"
        :model="batchBindChargeStandardForm"
        :rules="batchBindChargeStandardFormRules"
        label-width="120px"
      >
        <el-form-item label="选中车位" prop="parkingSpaceIds">
          <div class="selected-parking-spaces">
            <el-tag
              v-for="space in selectedRows"
              :key="space.id"
              size="small"
              class="space-tag"
            >
              {{ space.spaceNo }}
            </el-tag>
            <span class="selected-count">共 {{ selectedRows.length }} 个车位</span>
          </div>
        </el-form-item>
        
        <el-form-item label="收费类型" prop="chargeTypeId">
          <el-select 
            v-model="batchSelectedChargeType" 
            placeholder="请选择收费类型" 
            style="width: 100%"
            @change="handleBatchChargeTypeChange"
          >
            <el-option
              v-for="type in chargeTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="收费项目" prop="chargeItemId">
          <el-select 
            v-model="batchSelectedChargeItem" 
            placeholder="请选择收费项目" 
            style="width: 100%"
            :disabled="!batchSelectedChargeType"
            @change="handleBatchChargeItemChange"
          >
            <el-option
              v-for="item in chargeItems"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="收费标准" prop="chargeStandardId">
          <el-select 
            v-model="batchSelectedChargeStandard" 
            placeholder="请选择收费标准" 
            style="width: 100%"
            :disabled="!batchSelectedChargeItem"
            @change="handleBatchChargeStandardChange"
          >
            <el-option
              v-for="standard in chargeStandards"
              :key="standard.id"
              :label="standard.name"
              :value="standard.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="金额" prop="amountOverride">
          <el-input-number
            v-model="batchBindChargeStandardForm.amountOverride"
            :min="0"
            :precision="2"
            placeholder="请输入金额"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="当前是否可用" prop="isCurrent">
          <el-radio-group v-model="batchBindChargeStandardForm.isCurrent">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchBindChargeStandardDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchBindChargeStandardSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入车位对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入车位"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-dialog-content">
        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传.xlsx/.xls文件，且文件大小不超过10MB
            </div>
          </template>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <p>1. 请按照模板格式填写数据</p>
          <p>2. 车位类型请填写"产权车位/公共车位/租赁车位/访客车位/其他"</p>
          <p>3. 车位状态请填写"空置/自用/出租/出售/占用/报废"</p>
          <p>4. 确保必填字段都已填写完整</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button @click="handleDownloadTemplate">下载模板</el-button>
          <el-button
            type="primary"
            :loading="importLoading"
            @click="handleImport"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import {
  getParkingSpaceList,
  createParkingSpace,
  updateParkingSpace,
  deleteParkingSpace,
  batchDeleteParkingSpace,
  getParkingSpaceDetail,
  getParkingSpaceById,
  bindVehicleToParkingSpace,
  getAllChargeTypes,
  getChargeItemsByTypeId,
  getChargeStandardsByItemId,
  bindChargeStandardToParkingSpace,
  batchBindChargeStandardToParkingSpace,
  getChargeStandardById,
  unbindChargeStandardFromParkingSpace,
  unbindVehicleFromParkingSpace,
  importParkingSpaces,
  exportParkingSpaceTemplate,
  type ParkingSpace,
  type ParkingSpaceDetail,
  type ParkingSpaceQueryParams,
  type BindVehicleRequest,
  type ChargeType,
  type ChargeItem,
  type ChargeStandard,
  type BindChargeStandardRequest,
  type BatchBindChargeStandardRequest,
  PARKING_SPACE_TYPE_LABELS,
  PARKING_SPACE_STATUS_LABELS,
} from "@/api/parkingSpace";
import { findAllCells } from "@/api/cell";
import { searchVehicleByPlateNo } from "@/api/vehicle";
import { bindOwnerToParkingSpace, unbindOwnerFromParkingSpace } from "@/api/parkingSpace";
import { searchOwnerByName } from "@/api/owner";

// 响应式数据
const loading = ref(false);
const tableData = ref<ParkingSpace[]>([]);
const selectedRows = ref<ParkingSpace[]>([]);
// 搜索表单
const searchForm = reactive<ParkingSpaceQueryParams>({
  spaceNo: "",
  cellId: undefined,
  type: undefined,
  status: undefined,
});
const showFilterDialog = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const cellList = ref<any[]>([]);

// 详情弹窗相关
const detailDialogVisible = ref(false);
const detailData = ref<ParkingSpaceDetail | null>(null);
const detailLoading = ref(false);
const detailChargeStandards = ref<ChargeStandard[]>([]);
const unbindLoading = ref(false);
const detailBoundVehicles = ref<Array<{plateNo: string, vehicleId: number}>>([]);
const vehicleUnbindLoading = ref(false);
const ownerUnbindLoading = ref(false);

// 绑定车辆弹窗相关
const bindVehicleDialogVisible = ref(false);
const bindVehicleForm = reactive<Partial<BindVehicleRequest>>({
  parkingSpaceId: undefined,
  vehicleId: undefined,
  bindType: 1,
  authorizeStart: "",
  authorizeEnd: "",
});
const bindVehicleFormRef = ref<FormInstance>();
const vehicleList = ref<any[]>([]);
const vehicleSearchLoading = ref(false);

// 绑定住户弹窗相关
const bindOwnerDialogVisible = ref(false);
const currentParkingSpaceId = ref<number | null>(null);
const ownerSearchKeyword = ref("");
const ownerList = ref<{name: string, id: number}[]>([]);
const ownerSearchLoading = ref(false);
const selectedOwnerId = ref<number | null>(null);
const bindOwnerLoading = ref(false);

// 添加收费标准弹窗相关
const addChargeStandardDialogVisible = ref(false);
const chargeStandardForm = reactive<Partial<BindChargeStandardRequest>>({
  parkingSpaceId: undefined,
  chargeStandardId: undefined,
  amountOverride: 0,
  isCurrent: 1,
});
const chargeStandardFormRef = ref<FormInstance>();

// 三级联查数据
const chargeTypes = ref<ChargeType[]>([]);
const chargeItems = ref<ChargeItem[]>([]);
const chargeStandards = ref<ChargeStandard[]>([]);
const selectedChargeType = ref<number | undefined>();
const selectedChargeItem = ref<number | undefined>();
const selectedChargeStandard = ref<number | undefined>();

// 批量绑定收费标准相关
const batchBindChargeStandardDialogVisible = ref(false);
const batchBindChargeStandardFormRef = ref<FormInstance>();
const batchBindChargeStandardForm = reactive<BatchBindChargeStandardRequest>({
  parkingSpaceIds: [],
  chargeStandardId: 0,
  amountOverride: 0,
  isCurrent: 1,
});
const batchSelectedChargeType = ref<number | undefined>();
const batchSelectedChargeItem = ref<number | undefined>();
const batchSelectedChargeStandard = ref<number | undefined>();

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const selectedFile = ref<File | null>(null);
const uploadRef = ref();

// 绑定车辆表单验证规则
const bindVehicleFormRules: FormRules = {
  parkingSpaceId: [{ required: true, message: "车位ID不能为空", trigger: "blur" }],
  vehicleId: [{ required: true, message: "请选择车辆", trigger: "change" }],
  bindType: [{ required: true, message: "请选择绑定类型", trigger: "change" }],
  authorizeStart: [{ required: true, message: "请选择授权开始时间", trigger: "change" }],
  authorizeEnd: [{ required: true, message: "请选择授权结束时间", trigger: "change" }],
};

// 添加收费标准表单验证规则
const chargeStandardFormRules: FormRules = {
  parkingSpaceId: [{ required: true, message: "车位ID不能为空", trigger: "blur" }],
  chargeStandardId: [{ required: true, message: "请选择收费标准", trigger: "change" }],
  amountOverride: [{ required: true, message: "请输入金额", trigger: "blur" }],
  isCurrent: [{ required: true, message: "请选择是否当前标准", trigger: "change" }],
};

// 批量绑定收费标准表单验证规则
const batchBindChargeStandardFormRules: FormRules = {
  parkingSpaceIds: [{ required: true, message: "请选择车位", trigger: "change" }],
  chargeStandardId: [{ required: true, message: "请选择收费标准", trigger: "change" }],
  amountOverride: [{ required: true, message: "请输入金额", trigger: "blur" }],
  isCurrent: [{ required: true, message: "请选择是否当前标准", trigger: "change" }],
};

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 筛选表单（已废弃，使用searchForm替代）
const filterForm = reactive<ParkingSpaceQueryParams>({
  cellId: undefined,
  type: undefined,
  status: undefined,
});

// 表单数据
const formData = reactive<Partial<ParkingSpace>>({
  spaceNo: "",
  cellId: undefined,
  type: undefined,
  status: undefined,
  area: undefined,
  location: "",
  remark: "",
});

// 表单验证规则
const formRules: FormRules = {
  spaceNo: [{ required: true, message: "请输入车位编号", trigger: "blur" }],
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  type: [{ required: true, message: "请选择车位类型", trigger: "change" }],
  status: [{ required: true, message: "请选择车位状态", trigger: "change" }],
};

// 表单引用
const formRef = ref<FormInstance>();

// 计算属性
const currentQueryParams = computed(() => ({
  page: pagination.page - 1, // 后端从0开始
  limit: pagination.limit,
  spaceNo: searchForm.spaceNo || undefined,
  cellId: searchForm.cellId,
  type: searchForm.type,
  status: searchForm.status,
}));

// 获取类型标签
const getTypeLabel = (type: number) => {
  return PARKING_SPACE_TYPE_LABELS[type as keyof typeof PARKING_SPACE_TYPE_LABELS] || "未知";
};

// 获取状态标签
const getStatusLabel = (status: number) => {
  return PARKING_SPACE_STATUS_LABELS[status as keyof typeof PARKING_SPACE_STATUS_LABELS] || "未知";
};

// 获取类型标签样式
const getTypeTagType = (type: number): "info" | "success" | "warning" | "danger" => {
  const typeMap = {
    1: "success" as const, // 产权车位
    2: "info" as const, // 公共车位
    3: "warning" as const, // 租赁车位
    4: "info" as const, // 访客车位
    5: "danger" as const, // 其他
  };
  return typeMap[type as keyof typeof typeMap] || "info";
};

// 获取状态标签样式
const getStatusTagType = (status: number): "info" | "warning" | "danger" | "success" => {
  const typeMap = {
    1: "info" as const, // 空置
    2: "success" as const, // 自用
    3: "warning" as const, // 出租
    4: "danger" as const, // 出售
    5: "warning" as const, // 占用
    6: "danger" as const, // 报废
  };
  return typeMap[status as keyof typeof typeMap] || "info";
};


// 获取车位列表
const fetchParkingSpaceList = async () => {
  try {
    loading.value = true;
    const response = await getParkingSpaceList(currentQueryParams.value);
    console.log("车位列表响应:", response); // 添加调试日志
    if (response.code === 0 && response.data) {
      // 处理后端返回的数据结构
      if (response.data.list && Array.isArray(response.data.list)) {
        tableData.value = response.data.list;
        pagination.total = response.data.total || response.data.list.length;
      } else if (Array.isArray(response.data)) {
        tableData.value = response.data;
        pagination.total = response.data.length;
      } else {
        tableData.value = [];
        pagination.total = 0;
      }
    } else {
      ElMessage.error(response.message || "获取车位列表失败");
    }
  } catch (error) {
    console.error("获取车位列表失败:", error);
    ElMessage.error("获取车位列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取小区列表
const fetchCellList = async () => {
  try {
    const response = await findAllCells();
    if (response.code === 0 && response.data) {
      cellList.value = response.data;
    }
  } catch (error) {
    console.error("获取小区列表失败:", error);
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.page = 1;
  fetchParkingSpaceList();
};

// 重置搜索
const handleReset = () => {
  searchForm.spaceNo = "";
  searchForm.cellId = undefined;
  searchForm.type = undefined;
  searchForm.status = undefined;
  pagination.page = 1;
  fetchParkingSpaceList();
};

// 筛选处理
const handleFilter = () => {
  showFilterDialog.value = false;
  pagination.page = 1;
  fetchParkingSpaceList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchParkingSpaceList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchParkingSpaceList();
};

// 表格选择改变
const handleSelectionChange = (selection: ParkingSpace[]) => {
  selectedRows.value = selection;
};

// 添加车位
const handleAdd = () => {
  dialogTitle.value = "添加车位";
  Object.assign(formData, {
    spaceNo: "",
    cellId: undefined,
    type: undefined,
    status: undefined,
    area: undefined,
    location: "",
    remark: "",
  });
  dialogVisible.value = true;
};

// 编辑车位
const handleEdit = async (row: ParkingSpace) => {
  try {
    dialogTitle.value = "编辑车位";
    // 获取完整的车位信息用于回显
    const response = await getParkingSpaceById(row.id);
    if (response.code === 0 && response.data) {
      Object.assign(formData, {
        id: response.data.id,
        spaceNo: response.data.spaceNo,
        cellId: response.data.cellId,
        type: response.data.type,
        status: response.data.status,
        area: response.data.area,
        location: response.data.location || "",
        remark: response.data.remark || "",
      });
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取车位信息失败");
    }
  } catch (error) {
    console.error("获取车位信息失败:", error);
    ElMessage.error("获取车位信息失败");
  }
};

// 删除车位
const handleDelete = async (row: ParkingSpace) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除车位"${row.spaceNo}"吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    
    const response = await deleteParkingSpace(row.id);
    if (response.code === 0) {
      ElMessage.success("删除成功");
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除车位失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的车位");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedRows.value.length}个车位吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRows.value.map((row) => row.id);
    const response = await batchDeleteParkingSpace(ids);
    if (response.code === 0) {
      ElMessage.success("批量删除成功");
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    
    const response = formData.id
      ? await updateParkingSpace(formData as ParkingSpace)
      : await createParkingSpace(formData as ParkingSpace);

    if (response.code === 0) {
      ElMessage.success(formData.id ? "更新成功" : "创建成功");
      dialogVisible.value = false;
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败");
  }
};

// 详情
const handleDetail = async (row: ParkingSpace) => {
  try {
    detailLoading.value = true;
    const response = await getParkingSpaceDetail(row.id);
    if (response.code === 0 && response.data) {
      detailData.value = response.data;
      
      // 查询收费标准详情
      await fetchDetailChargeStandards(response.data.chargeStandardIds);
      
      // 查询绑定车辆详情
      await fetchDetailBoundVehicles(response.data.boundVehicles);
      
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取车位详情失败");
    }
  } catch (error) {
    console.error("获取车位详情失败:", error);
    ElMessage.error("获取车位详情失败");
  } finally {
    detailLoading.value = false;
  }
};

// 绑定住户
const handleBindResident = (row: ParkingSpace) => {
  currentParkingSpaceId.value = row.id;
  ownerSearchKeyword.value = "";
  ownerList.value = [];
  selectedOwnerId.value = null;
  bindOwnerDialogVisible.value = true;
};

// 搜索业主
const searchOwners = async (keyword: string) => {
  if (!keyword.trim()) {
    ownerList.value = [];
    return;
  }
  
  try {
    ownerSearchLoading.value = true;
    const response = await searchOwnerByName(keyword);
    if (response.code === 0) {
      ownerList.value = response.data || [];
    } else {
      ElMessage.error(response.message || "搜索业主失败");
      ownerList.value = [];
    }
  } catch (error) {
    console.error("搜索业主失败:", error);
    ElMessage.error("搜索业主失败");
    ownerList.value = [];
  } finally {
    ownerSearchLoading.value = false;
  }
};

// 确认绑定住户
const confirmBindOwner = async () => {
  if (!selectedOwnerId.value || !currentParkingSpaceId.value) {
    ElMessage.warning("请选择要绑定的住户");
    return;
  }
  
  try {
    bindOwnerLoading.value = true;
    const response = await bindOwnerToParkingSpace(currentParkingSpaceId.value, selectedOwnerId.value);
    if (response.code === 0) {
      ElMessage.success("绑定住户成功");
      bindOwnerDialogVisible.value = false;
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "绑定住户失败");
    }
  } catch (error) {
    console.error("绑定住户失败:", error);
    ElMessage.error("绑定住户失败");
  } finally {
    bindOwnerLoading.value = false;
  }
};

// 绑定车辆
const handleBindVehicle = (row: ParkingSpace) => {
  bindVehicleForm.parkingSpaceId = row.id;
  bindVehicleForm.vehicleId = undefined;
  bindVehicleForm.bindType = 1;
  bindVehicleForm.authorizeStart = "";
  bindVehicleForm.authorizeEnd = "";
  bindVehicleDialogVisible.value = true;
  // 清空车辆列表，等待用户输入搜索
  vehicleList.value = [];
};

// 添加收费标准
const handleAddChargingStandard = (row: ParkingSpace) => {
  chargeStandardForm.parkingSpaceId = row.id;
  chargeStandardForm.chargeStandardId = undefined;
  chargeStandardForm.amountOverride = 0;
  chargeStandardForm.isCurrent = 1;
  
  // 重置三级联查
  selectedChargeType.value = undefined;
  selectedChargeItem.value = undefined;
  selectedChargeStandard.value = undefined;
  chargeItems.value = [];
  chargeStandards.value = [];
  
  addChargeStandardDialogVisible.value = true;
  fetchChargeTypes();
};


// 搜索车辆
const searchVehicles = async (query: string) => {
  if (!query) {
    vehicleList.value = [];
    return;
  }
  
  try {
    vehicleSearchLoading.value = true;
    // 调用车辆搜索接口
    const response = await searchVehicleByPlateNo(query);
    if (response.code === 0 && response.data) {
      vehicleList.value = response.data;
    } else {
      vehicleList.value = [];
    }
  } catch (error) {
    console.error("搜索车辆失败:", error);
    vehicleList.value = [];
  } finally {
    vehicleSearchLoading.value = false;
  }
};

// 提交绑定车辆
const handleBindVehicleSubmit = async () => {
  if (!bindVehicleFormRef.value) return;

  try {
    await bindVehicleFormRef.value.validate();
    
    const response = await bindVehicleToParkingSpace(bindVehicleForm as BindVehicleRequest);
    
    if (response.code === 0) {
      ElMessage.success("绑定车辆成功");
      bindVehicleDialogVisible.value = false;
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "绑定车辆失败");
    }
  } catch (error) {
    console.error("绑定车辆失败:", error);
    ElMessage.error("绑定车辆失败");
  }
};

// 禁用授权开始时间的日期（只能选择当前及以后的时间）
const disabledStartDate = (time: Date) => {
  const now = new Date();
  now.setHours(0, 0, 0, 0);
  return time.getTime() < now.getTime();
};

// 禁用授权开始时间的时间（如果选择今天，则只能选择当前时间及以后）
const disabledStartTime = (time: Date) => {
  const now = new Date();
  const selectedDate = new Date(time);
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  selectedDate.setHours(0, 0, 0, 0);
  
  // 如果选择的是今天，则禁用当前时间之前的时间
  if (selectedDate.getTime() === today.getTime()) {
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    return {
      disabledHours: () => {
        const hours = [];
        for (let i = 0; i < currentHour; i++) {
          hours.push(i);
        }
        return hours;
      },
      disabledMinutes: (hour: number) => {
        if (hour === currentHour) {
          const minutes = [];
          for (let i = 0; i < currentMinute; i++) {
            minutes.push(i);
          }
          return minutes;
        }
        return [];
      },
      disabledSeconds: (hour: number, minute: number) => {
        if (hour === currentHour && minute === currentMinute) {
          const seconds = [];
          for (let i = 0; i < now.getSeconds(); i++) {
            seconds.push(i);
          }
          return seconds;
        }
        return [];
      }
    };
  }
  return {};
};

// 禁用授权结束时间的日期
const disabledEndDate = (time: Date) => {
  if (!bindVehicleForm.authorizeStart) return false;
  
  const startDate = new Date(bindVehicleForm.authorizeStart);
  const endDate = new Date(time);
  
  // 结束时间不能早于开始时间
  if (endDate.getTime() < startDate.getTime()) {
    return true;
  }
  
  // 如果是临时绑定，结束时间不能超过开始时间的一周
  if (bindVehicleForm.bindType === 2) {
    const maxEndDate = new Date(startDate);
    maxEndDate.setDate(maxEndDate.getDate() + 7);
    return endDate.getTime() > maxEndDate.getTime();
  }
  
  return false;
};

// 禁用授权结束时间的时间
const disabledEndTime = (time: Date) => {
  if (!bindVehicleForm.authorizeStart) return {};
  
  const startDate = new Date(bindVehicleForm.authorizeStart);
  const endDate = new Date(time);
  
  // 如果结束日期和开始日期是同一天，则结束时间不能早于开始时间
  if (startDate.toDateString() === endDate.toDateString()) {
    const startHour = startDate.getHours();
    const startMinute = startDate.getMinutes();
    const startSecond = startDate.getSeconds();
    
    return {
      disabledHours: () => {
        const hours = [];
        for (let i = 0; i < startHour; i++) {
          hours.push(i);
        }
        return hours;
      },
      disabledMinutes: (hour: number) => {
        if (hour === startHour) {
          const minutes = [];
          for (let i = 0; i < startMinute; i++) {
            minutes.push(i);
          }
          return minutes;
        }
        return [];
      },
      disabledSeconds: (hour: number, minute: number) => {
        if (hour === startHour && minute === startMinute) {
          const seconds = [];
          for (let i = 0; i < startSecond; i++) {
            seconds.push(i);
          }
          return seconds;
        }
        return [];
      }
    };
  }
  
  return {};
};

// 获取收费类型列表
const fetchChargeTypes = async () => {
  try {
    const response = await getAllChargeTypes();
    if (response.code === 0 && response.data) {
      chargeTypes.value = response.data;
    }
  } catch (error) {
    console.error("获取收费类型失败:", error);
    ElMessage.error("获取收费类型失败");
  }
};

// 获取收费项目列表
const fetchChargeItems = async (chargeTypeId: number) => {
  try {
    const response = await getChargeItemsByTypeId(chargeTypeId);
    if (response.code === 0 && response.data) {
      chargeItems.value = response.data;
    }
  } catch (error) {
    console.error("获取收费项目失败:", error);
    ElMessage.error("获取收费项目失败");
  }
};

// 获取收费标准列表
const fetchChargeStandards = async (chargeItemId: number) => {
  try {
    const response = await getChargeStandardsByItemId(chargeItemId);
    if (response.code === 0 && response.data) {
      chargeStandards.value = response.data;
    }
  } catch (error) {
    console.error("获取收费标准失败:", error);
    ElMessage.error("获取收费标准失败");
  }
};

// 收费类型改变
const handleChargeTypeChange = (chargeTypeId: number) => {
  selectedChargeItem.value = undefined;
  selectedChargeStandard.value = undefined;
  chargeItems.value = [];
  chargeStandards.value = [];
  chargeStandardForm.chargeStandardId = undefined;
  chargeStandardForm.amountOverride = 0;
  
  if (chargeTypeId) {
    fetchChargeItems(chargeTypeId);
  }
};

// 收费项目改变
const handleChargeItemChange = (chargeItemId: number) => {
  selectedChargeStandard.value = undefined;
  chargeStandards.value = [];
  chargeStandardForm.chargeStandardId = undefined;
  chargeStandardForm.amountOverride = 0;
  
  if (chargeItemId) {
    fetchChargeStandards(chargeItemId);
  }
};

// 收费标准改变
const handleChargeStandardChange = (chargeStandardId: number) => {
  chargeStandardForm.chargeStandardId = chargeStandardId;
  
  // 自动填充标准金额
  const selectedStandard = chargeStandards.value.find(item => item.id === chargeStandardId);
  if (selectedStandard) {
    chargeStandardForm.amountOverride = selectedStandard.price;
  }
};

// 提交添加收费标准
const handleAddChargeStandardSubmit = async () => {
  if (!chargeStandardFormRef.value) return;

  try {
    await chargeStandardFormRef.value.validate();
    
    const response = await bindChargeStandardToParkingSpace(chargeStandardForm as BindChargeStandardRequest);
    
    if (response.code === 0) {
      ElMessage.success("添加收费标准成功");
      addChargeStandardDialogVisible.value = false;
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "添加收费标准失败");
    }
  } catch (error) {
    console.error("添加收费标准失败:", error);
    ElMessage.error("添加收费标准失败");
  }
};

// 添加收费标准
const handleBatchBindChargeStandard = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要添加收费标准的车位");
    return;
  }
  
  // 重置表单
  batchBindChargeStandardForm.parkingSpaceIds = selectedRows.value.map(row => row.id);
  batchBindChargeStandardForm.chargeStandardId = 0;
  batchBindChargeStandardForm.amountOverride = 0;
  batchBindChargeStandardForm.isCurrent = 1;
  
  // 重置选择状态
  batchSelectedChargeType.value = undefined;
  batchSelectedChargeItem.value = undefined;
  batchSelectedChargeStandard.value = undefined;
  
  // 清空数据
  chargeItems.value = [];
  chargeStandards.value = [];
  
  // 打开对话框
  batchBindChargeStandardDialogVisible.value = true;
  
  // 获取收费类型
  fetchChargeTypes();
};

// 批量收费类型改变
const handleBatchChargeTypeChange = (chargeTypeId: number) => {
  batchSelectedChargeItem.value = undefined;
  batchSelectedChargeStandard.value = undefined;
  chargeItems.value = [];
  chargeStandards.value = [];
  
  if (chargeTypeId) {
    fetchChargeItems(chargeTypeId);
  }
};

// 批量收费项目改变
const handleBatchChargeItemChange = (chargeItemId: number) => {
  batchSelectedChargeStandard.value = undefined;
  chargeStandards.value = [];
  
  if (chargeItemId) {
    fetchChargeStandards(chargeItemId);
  }
};

// 批量收费标准改变
const handleBatchChargeStandardChange = (chargeStandardId: number) => {
  batchBindChargeStandardForm.chargeStandardId = chargeStandardId;
  
  // 自动填充标准金额
  const selectedStandard = chargeStandards.value.find(item => item.id === chargeStandardId);
  if (selectedStandard) {
    batchBindChargeStandardForm.amountOverride = selectedStandard.price;
    
    // 清除金额字段的验证错误
    if (batchBindChargeStandardFormRef.value) {
      batchBindChargeStandardFormRef.value.clearValidate('amountOverride');
    }
  }
};

// 提交添加收费标准
const handleBatchBindChargeStandardSubmit = async () => {
  if (!batchBindChargeStandardFormRef.value) return;

  try {
    await batchBindChargeStandardFormRef.value.validate();
    
    const response = await batchBindChargeStandardToParkingSpace(batchBindChargeStandardForm);
    
    if (response.code === 0) {
      ElMessage.success("添加收费标准成功");
      batchBindChargeStandardDialogVisible.value = false;
      fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "添加收费标准失败");
    }
  } catch (error) {
    console.error("添加收费标准失败:", error);
    ElMessage.error("添加收费标准失败");
  }
};

// 组件挂载
// 查询车位详情中的收费标准
const fetchDetailChargeStandards = async (chargeStandardIds: string) => {
  if (!chargeStandardIds) {
    detailChargeStandards.value = [];
    return;
  }
  
  try {
    const ids = chargeStandardIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
    const promises = ids.map(id => getChargeStandardById(id));
    const responses = await Promise.all(promises);
    
    detailChargeStandards.value = responses
      .filter(response => response.code === 0 && response.data)
      .map(response => response.data);
  } catch (error) {
    console.error("查询收费标准失败:", error);
    detailChargeStandards.value = [];
  }
};

// 查询绑定车辆详情
const fetchDetailBoundVehicles = async (boundVehicles: string) => {
  if (!boundVehicles) {
    detailBoundVehicles.value = [];
    return;
  }
  
  try {
    // 解析绑定车辆字符串（格式：川A666666,川B44666）
    const plateNos = boundVehicles.split(',').map(plate => plate.trim()).filter(plate => plate);
    
    // 为每个车牌号查询车辆信息
    const promises = plateNos.map(plateNo => searchVehicleByPlateNo(plateNo));
    const responses = await Promise.all(promises);
    
    detailBoundVehicles.value = responses
      .filter(response => response.code === 0 && response.data && response.data.length > 0)
      .map(response => ({
        plateNo: response.data[0].plateNo,
        vehicleId: response.data[0].id
      }));
  } catch (error) {
    console.error("查询绑定车辆失败:", error);
    detailBoundVehicles.value = [];
  }
};

// 解除绑定车辆
const handleUnbindVehicle = async (vehicleId: number) => {
  if (!detailData.value) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要解除车辆与车位 ${detailData.value.spaceNo} 的绑定吗？`,
      '确认解除绑定',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    vehicleUnbindLoading.value = true;
    const response = await unbindVehicleFromParkingSpace({
      parkingSpaceId: detailData.value.id,
      vehicleId: vehicleId
    });
    
    if (response.code === 0) {
      ElMessage.success("解除绑定成功");
      // 刷新详情和列表
      await fetchParkingSpaceList();
      await handleDetail({ id: detailData.value.id } as ParkingSpace);
    } else {
      ElMessage.error(response.message || "解除绑定失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("解除绑定失败:", error);
      ElMessage.error("解除绑定失败");
    }
  } finally {
    vehicleUnbindLoading.value = false;
  }
};

// 解除绑定住户
const handleUnbindOwner = async () => {
  if (!detailData.value) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要解除业主 ${detailData.value.ownerName} 与车位 ${detailData.value.spaceNo} 的绑定吗？`,
      '确认解除绑定',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    ownerUnbindLoading.value = true;
    const response = await unbindOwnerFromParkingSpace(detailData.value.id);
    
    if (response.code === 0) {
      ElMessage.success("解除绑定成功");
      // 刷新详情和列表
      await fetchParkingSpaceList();
      await handleDetail({ id: detailData.value.id } as ParkingSpace);
    } else {
      ElMessage.error(response.message || "解除绑定失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("解除绑定失败:", error);
      ElMessage.error("解除绑定失败");
    }
  } finally {
    ownerUnbindLoading.value = false;
  }
};

// 解除绑定收费标准
const handleUnbindChargeStandard = async (chargeStandardId: number) => {
  if (!detailData.value) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要解除车位 ${detailData.value.spaceNo} 的收费标准绑定吗？`,
      '确认解除绑定',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    unbindLoading.value = true;
    const response = await unbindChargeStandardFromParkingSpace({
      parkingSpaceId: detailData.value.id,
      chargeStandardId: chargeStandardId,
    });
    
    if (response.code === 0) {
      ElMessage.success("解除绑定成功");
      // 刷新车位列表数据
      await fetchParkingSpaceList();
      // 重新获取车位详情
      await handleDetail({ id: detailData.value.id } as ParkingSpace);
    } else {
      ElMessage.error(response.message || "解除绑定失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("解除绑定失败:", error);
      ElMessage.error("解除绑定失败");
    }
  } finally {
    unbindLoading.value = false;
  }
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  selectedFile.value = null;
  // 重置上传组件状态
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 文件选择处理
const handleFileChange = (file: any) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error('只能上传.xlsx/.xls文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }

  selectedFile.value = file.raw;
  return true;
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const response = await exportParkingSpaceTemplate();
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '车位导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('模板下载成功');
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
};

// 处理导入
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning("请先选择要导入的文件");
    return;
  }

  importLoading.value = true;
  try {
    const response = await importParkingSpaces(selectedFile.value);
    if (response.code === 0) {
      ElMessage.success("导入成功");
      importDialogVisible.value = false;
      selectedFile.value = null;
      // 重置上传组件状态
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
      // 刷新列表
      await fetchParkingSpaceList();
    } else {
      ElMessage.error(response.message || "导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  } finally {
    importLoading.value = false;
  }
};

onMounted(() => {
  fetchParkingSpaceList();
  fetchCellList();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button--text) {
  padding: 0;
  margin-right: 8px;
}

:deep(.el-tag) {
  font-size: 12px;
}

.detail-content {
  padding: 20px 0;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-row .label {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
  margin-right: 12px;
}

.detail-row .value {
  color: #303133;
  flex: 1;
}

.selected-parking-spaces {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.selected-parking-spaces .space-tag {
  margin-right: 4px;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

.charge-standards-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.charge-standard-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.standard-info {
  color: #303133;
  font-size: 14px;
}

/* 导入对话框样式 */
.import-dialog-content {
  padding: 10px 0;
}

.upload-area {
  margin-bottom: 20px;
}

.import-tips {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.import-tips h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 14px;
}

.import-tips p {
  margin: 5px 0;
  font-size: 13px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 绑定车辆列表样式 */
.bound-vehicles-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.bound-vehicle-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.vehicle-info {
  font-weight: 500;
  color: #495057;
}

.bound-owner-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.owner-info {
  font-weight: 500;
  color: #495057;
}

/* 绑定住户弹窗样式 */
.bind-owner-content {
  padding: 20px 0;
}

.search-section {
  margin-bottom: 20px;
}

.owner-list-section h4 {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
}

.owner-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.owner-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.owner-item:last-child {
  border-bottom: none;
}

.owner-item:hover {
  background-color: #f5f7fa;
}

.owner-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.owner-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.no-results {
  text-align: center;
  padding: 40px 0;
}

.loading {
  text-align: center;
  padding: 20px 0;
  color: #909399;
  font-size: 14px;
}
</style>
